import { useCallback, useEffect, useRef } from 'react';
import { useAuthStore } from '@/store/auth';
import { useRouter } from 'next/navigation';
import { LoginCredentials } from '@/types/auth';

export const useAuth = () => {
  const router = useRouter();
  const authChecked = useRef(false);
  const { 
    user, 
    token, 
    isAuthenticated, 
    isLoading, 
    login: storeLogin, 
    logout: storeLogout,
    register: storeRegister,
    checkAuth,
    setLoading
  } = useAuthStore();

  useEffect(() => {
    const checkAuthStatus = async () => {
      if (!authChecked.current) {
        authChecked.current = true;
        await checkAuth();
      }
    };
    
    checkAuthStatus();
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const login = useCallback(async (credentials: LoginCredentials) => {
    await storeLogin(credentials);
    router.push('/dashboard');
  }, [storeLogin, router]);

  const register = useCallback(async (data: any) => {
    await storeRegister(data);
    router.push('/dashboard');
  }, [storeRegister, router]);

  const logout = useCallback(async () => {
    await storeLogout();
    router.push('/login');
  }, [storeLogout, router]);

  const redirectToLogin = useCallback(() => {
    router.push('/login');
  }, [router]);

  return {
    user,
    token,
    isAuthenticated,
    isLoading,
    login,
    logout,
    register,
    redirectToLogin,
    setLoading
  };
}; 